package com.xiaobao.coalproperty.module.user.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.xiaobao.coalproperty.App;
import com.xiaobao.coalproperty.R;
import com.xiaobao.coalproperty.module.home.model.entity.BlankEntity;
import com.xiaobao.coalproperty.module.user.model.entity.UploadPicEntity;
import com.xiaobao.coalproperty.other.base.BaseActivity;
import com.xiaobao.coalproperty.other.constant.UrlConstant;
import com.xiaobao.coalproperty.other.util.HttpHelperUtils;
import com.xiaobao.coalproperty.other.util.UserHelperUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

public class UserDataActivity extends BaseActivity {

    @BindView(R.id.user_head)
    CircleImageView ivHead;
    @BindView(R.id.user_name)
    EditText edtName;
    @BindView(R.id.user_gender)
    TextView tvGender;
    @BindView(R.id.user_birthday)
    TextView tvBirthday;
    @BindView(R.id.user_address)
    TextView tvAddress;

    private List<String> genderList;
    private OptionsPickerView mOptionsPickerView;
    private int type = 0;

    private List<LocalMedia> mLocalMedia;


    @Override
    protected int getContentView() {
        return R.layout.activity_user_data;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setLeftClickFinish();
        setTitle("个人信息");

        genderList = new ArrayList<>();
        genderList.add("男");
        genderList.add("女");

        mOptionsPickerView = new OptionsPickerView.Builder(this, mOnOptionsSelectListener).build();

        edtName.setCursorVisible(false);
        edtName.setOnClickListener(mOnClickListener);
        edtName.addTextChangedListener(mTextWatcher);

        if (UserHelperUtils.getInstance().getCenter() != null) {
            Glide.with(this).load(UserHelperUtils.getInstance().getCenter().getData().getAvatar());
            edtName.setText(UserHelperUtils.getInstance().getCenter().getData().getNickname());
            String gendre = UserHelperUtils.getInstance().getCenter().getData().getSex();
            if (!gendre.equals("")) {
                tvGender.setText(gendre.equals("1") ? "男" : "女");
            }
            tvBirthday.setText(UserHelperUtils.getInstance().getCenter().getData().getBirthday());
            String address = UserHelperUtils.getInstance().getCenter().getData().getProvince_name() +
                    UserHelperUtils.getInstance().getCenter().getData().getArea_name() +
                    UserHelperUtils.getInstance().getCenter().getData().getCounty_name();
            tvAddress.setText(address);
        }
    }

    public void onUserDataSaveClick(View view) {
        showToast("保存成功");
    }

    public void onUserDataGenderClick(View view) {
        mOptionsPickerView.setPicker(genderList);
        mOptionsPickerView.show();
        type = 1;
    }

    public void onUserDataBirthdayClick(View view) {
        mOptionsPickerView.setPicker(App.getContext().getStartTimeList());
        mOptionsPickerView.show();
        type = 2;
    }

    public void onUserDataHeadClick(View view) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .compress(true)
                .forResult(1);
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_name:
                    edtName.setCursorVisible(true);
                    edtName.setFocusableInTouchMode(true);
                    edtName.requestFocus();
                    break;
            }
        }
    };

    private OptionsPickerView.OnOptionsSelectListener mOnOptionsSelectListener = new OptionsPickerView.OnOptionsSelectListener() {
        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            if (type == 1) {
                tvGender.setText(genderList.get(options1));
                submit(HttpHelperUtils.getInstance().managerSubmitParams("", "", genderList.get(options1), "", "", "", ""));
            } else if (type == 2) {
                tvBirthday.setText(App.getContext().getStartTimeList().get(options1));
                submit(HttpHelperUtils.getInstance().managerSubmitParams("", "", "", App.getContext().getStartTimeList().get(options1), "", "", ""));
            }
        }
    };

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //文字变化
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //开始输入
        }

        @Override
        public void afterTextChanged(Editable s) {
            //输入结束
            submit(HttpHelperUtils.getInstance().managerSubmitParams("", edtName.getText().toString(), "", "", "", "", ""));
        }
    };

    // 1.media.getPath(); 为原图path 2.media.getCutPath();为裁剪后path 3.media.getCompressPath();为压缩后path
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    mLocalMedia = PictureSelector.obtainMultipleResult(data);
                    uploadHeadImage();
                    break;
            }
        }
    }

    private void submit(Map<String, String> params) {
        OkHttpUtils.post().url(UrlConstant.URL_MANAGER_SUBMIT)
                .params(params)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    BlankEntity entity = new Gson().fromJson(response, BlankEntity.class);
                    showToast(entity.getMsg());
                } catch (Exception e) {
                }
            }
        });
    }

    private void uploadHeadImage() {
        File file;
        if (mLocalMedia != null && mLocalMedia.size() > 0) {
            if (mLocalMedia.get(0).isCut()) {
                file = new File(mLocalMedia.get(0).getCutPath());
            } else {
                file = new File(mLocalMedia.get(0).getPath());
            }
            String filename = UserHelperUtils.getInstance().getHashId() + "" + System.currentTimeMillis() + "" + file.getName();
            OkHttpUtils.post().url(UrlConstant.URL_UPLOAD_PICTURE)
                    .addFile("uploadname", filename, file)
                    .params(HttpHelperUtils.getInstance().uploadPictureParams())
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        UploadPicEntity entity = new Gson().fromJson(response, UploadPicEntity.class);
                        if (entity.getCode() == 0) {
                            submit(HttpHelperUtils.getInstance().managerSubmitParams(entity.getData(), "", "", "", "", "", ""));
                        }
                    } catch (Exception e) {
                    }
                }
            });
        }
    }
}
